In [55]:
    
import numpy as np
import cv2
import matplotlib.pyplot as plt
    
In [61]:
    
img_path = r'C:\Users\USER\Downloads\trial2.jpg'
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #matplotlib是RGB,但是opencv是BGR
plt.imshow(img)
plt.show()
    
    
In [62]:
    
img
    
    Out[62]:
In [63]:
    
import numpy as np 
import cv2 
face_cascade = cv2.CascadeClassifier(r'C:\Users\USER\Anaconda3\envs\tensorflow\Library\etc\haarcascades\haarcascade_frontalface_default.xml') 
eye_cascade = cv2.CascadeClassifier(r'C:\Users\USER\Anaconda3\envs\tensorflow\Library\etc\haarcascades\haarcascade_eye.xml') 
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#Now we find the faces in the image. If faces are found, it returns the positions of detected
#faces as Rect(x,y,w,h). Once we get these locations, we can create a ROI for the face and
#apply eye detection on this ROI (since eyes are always on the face !!! ).
faces = face_cascade.detectMultiScale(gray, 1.3, 5) 
for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    
    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
    
In [7]:
    
import cv2
import numpy as np
import matplotlib.pyplot as plt
import dicom as pdicom
import os
import glob
%matplotlib inline
    
In [10]:
    
import pandas as pd
import scipy.ndimage
from skimage import measure, morphology
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
    
In [11]:
    
INPUT_FOLDER = r'C:\Users\USER\Downloads\CT_image_tutorial\dicom_dir'
patients = os.listdir(INPUT_FOLDER)
patients.sort()
    
In [14]:
    
#Collect all dicom images
lstFilesDCM = []
def load_scan2(path):
    for dirName, subdirList, fileList in os.walk(path):
        for filename in fileList:
            if '.dcm' in filename.lower(): #確認是dcm檔案
                lstFilesDCM.append(os.path.join(dirName,filename))
                #print(lstFilesDCM)
    return lstFilesDCM
first_patient = load_scan2(INPUT_FOLDER)
#print(first_patient)
    
In [16]:
    
# Get ref file
RefDs = pdicom.read_file(lstFilesDCM[0])
# Load dims based on rows, cols, slices(Z-axis)
ConstPixelDims = (int(RefDs.Rows), int(RefDs.Columns), len(lstFilesDCM)) #維度跟著row,col,還有Z軸是slices
# Load spacing values (in mm)
ConstPixelSpacing = (float(RefDs.PixelSpacing[0]) , float(RefDs.PixelSpacing[1]), float(RefDs.SliceThickness))
    
In [17]:
    
x = np.arange(0.0, (ConstPixelDims[0]+1)*ConstPixelSpacing[0], ConstPixelSpacing[0] )
y = np.arange(0.0, (ConstPixelDims[1]+1)*ConstPixelSpacing[1], ConstPixelSpacing[1] )
z = np.arange(0.0, (ConstPixelDims[2]+1)*ConstPixelSpacing[2], ConstPixelSpacing[2] )
    
In [18]:
    
# The array is based on ConstPixelDims
ArrayDicom = np.zeros(ConstPixelDims, dtype = RefDs.pixel_array.dtype)
# loop through all DICOM files:
for filenameDCM in lstFilesDCM:
    # read the file
    ds = pdicom.read_file(filenameDCM)
    # store the raw image data
    ArrayDicom[:, :, lstFilesDCM.index(filenameDCM)] = ds.pixel_array
    
In [23]:
    
plt.figure(dpi=1600)
plt.axes().set_aspect('equal', 'datalim')
plt.set_cmap(plt.gray())
plt.pcolormesh(x, y, np.flipud(ArrayDicom[:, :, 99]))
    
    Out[23]:
    
In [36]:
    
plt.figure(dpi=1600)
plt.axes().set_aspect('equal', 'datalim')
plt.set_cmap(plt.gray())
plt.pcolormesh(x, y, np.flipud(ArrayDicom[:, :, 2]))
    
    Out[36]:
    
In [37]:
    
# 落在邊界外是-2000,要先把他們變成0
def get_pixels_hu(slices):
    image = np.stack([s.pixel_array for s in slices])
    # Convert to int16 (from sometimes int16), 
    # should be possible as values should always be low enough (<32k)
    image = image.astype(np.int16)
    # Set outside-of-scan pixels to 0
    # The intercept is usually -1024, so air is approximately 0
    image[image == -2000] = 0
    
    # Convert to Hounsfield units (HU)
    for slice_number in range(len(slices)):
        
        intercept = slices[slice_number].RescaleIntercept
        slope = slices[slice_number].RescaleSlope
        
        if slope != 1:
            image[slice_number] = slope * image[slice_number].astype(np.float64)
            image[slice_number] = image[slice_number].astype(np.int16)
            
        image[slice_number] += np.int16(intercept)
    
    return np.array(image, dtype=np.int16)
    
In [40]:
    
    
    
In [ ]: